// ==UserScript==
// @name         商品查重助手
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  在找源头网站商品页面添加查重按钮，自动检查商品是否已在ERP系统中存在
// @author       Your name
// @match        https://*.zhaoyuantou.com/*
// @grant        GM_xmlhttpRequest
// @connect      apiweb.erp321.com
// ==/UserScript==

(function() {
    'use strict';

    // 调试模式开关
    const DEBUG_MODE = true;

    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        .check-product-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-left: 8px;
            width: 24px;
            height: 24px;
            border: 1px solid #ea4c89;
            border-radius: 50%;
            color: #ea4c89;
            cursor: pointer;
            background: white;
            padding: 0;
        }
        .check-product-btn:hover {
            background: #ea4c89;
            color: white;
        }
        .check-product-btn svg {
            width: 14px;
            height: 14px;
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            width: 400px;
            max-width: 90%;
        }

        .modal-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 16px;
            color: #333;
        }

        .modal-section {
            margin-bottom: 16px;
        }

        .modal-section-title {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 8px;
            color: #666;
        }

        .char-group {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .char-option {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            color: #333;
            background: #f5f5f5;
            border: none;
            transition: all 0.2s ease;
        }

        .char-option.selected {
            background: #ea4c89;
            color: white;
        }

        .char-option:hover:not(.selected) {
            background: #e0e0e0;
        }
        .radio-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .radio-label {
            display: flex;
            align-items: center;
            cursor: pointer;
            font-size: 14px;
            color: #333;
            padding: 8px 12px;
            margin: -4px -8px;
            border-radius: 4px;
            transition: background-color 0.2s ease;
        }

        .radio-label:hover {
            background-color: rgba(234, 76, 137, 0.1);
        }

        .radio-label input {
            margin-right: 12px;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 20px;
        }

        .modal-button {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            border: none;
        }

        .modal-button-primary {
            background-color: #ea4c89;
            color: white;
        }

        .modal-button-primary:hover {
            background-color: #f082ac;
        }

        .modal-button-secondary {
            background-color: #e0e0e0;
            color: #333;
        }

        .modal-button-secondary:hover {
            background-color: #d0d0d0;
        }
    `;

    document.head.appendChild(style);

    // 显示调试信息
    function showDebugInfo(info) {
        if (!DEBUG_MODE) return;
        console.log('[DEBUG]', info);
    }

    // 添加检查按钮
    function addCheckButtons() {
        const colorDivs = document.querySelectorAll('.spec-item-lists > div');
        colorDivs.forEach(div => {
            if (!div.querySelector('.check-product-btn')) {
                const btn = document.createElement('button');
                btn.className = 'check-product-btn';
                btn.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 15l6 6m-11-4a7 7 0 110-14 7 7 0 010 14z"></path></svg>';
                btn.onclick = () => checkProduct(div);
                div.appendChild(btn);
            }
        });
    }

    // 拼音声母可能的首字母
    const PINYIN_INITIAL_CONSONANT_LETTERS = 'ABCDEFGHJKLMNOPQRSTWXYZ'.split('');
    // 拼音声母对应的边界中文
    const PINYIN_BOUNDARY_CHAR = '驁簿錯鵽樲鰒餜靃攟鬠纙鞪黁漚曝裠鶸蜶籜鶩鑂韻糳'.split('');

    // 获取汉字拼音首字母
    function getChinesePinyinAbbreviation(str) {
        // 空字符串直接返回
        if (!str) {
            return '';
        }
        if (str.length > 1) {
            return str.split('').map(getChinesePinyinAbbreviation).join('');
        }
        // 判断字符是否为中文,不是中文返回原字符
        if (/[^\u4e00-\u9fa5]/.test(str)) {
            return str;
        }
        const index = PINYIN_BOUNDARY_CHAR.findIndex((char) => {
            return char.localeCompare(str, 'zh-CN-u-co-pinyin') >= 0;
        });
        return PINYIN_INITIAL_CONSONANT_LETTERS[index];
    }

    // 获取店铺名称条件
    function getShopCondition() {
        const shopName = document.querySelector('.merchand-name.pointer')?.textContent.trim() || '';
        let condition;
        
        // 获取前三个字符的拼音首字母
        const firstTwoChars = Array.from(shopName).slice(0, 2);
        const pinyinCode = getChinesePinyinAbbreviation(firstTwoChars.join(''));
        condition = pinyinCode + '*';
        
        if (DEBUG_MODE) {
            showDebugInfo({
                step: '获取店铺条件',
                原始店铺名: shopName,
                店铺名前两字: firstTwoChars,
                拼音首字母: pinyinCode,
                处理后条件: condition
            });
        }
        
        return condition;
    }

    function getColorCondition(colorDiv) {
        const colorSpan = colorDiv.querySelector('span[style="max-width: 108px;"]');
        const colorText = colorSpan ? colorSpan.textContent.trim() : '';
        const condition = colorText.slice(0, 2) + '*';
        
        if (DEBUG_MODE) {
            showDebugInfo({
                step: '获取颜色条件',
                原始颜色文本: colorText,
                处理后条件: condition
            });
        }
        
        return condition;
    }

    // 创建模态框
    function createModal(shopName, colorText, onConfirm) {
        const modal = document.createElement('div');
        modal.className = 'modal-overlay';

        const content = document.createElement('div');
        content.className = 'modal-content';

        // 标题
        const title = document.createElement('div');
        title.className = 'modal-title';
        title.textContent = '选择查询条件';

        // 店铺名称选项
        const shopSection = document.createElement('div');
        shopSection.className = 'modal-section';

        const shopTitle = document.createElement('div');
        shopTitle.className = 'modal-section-title';
        shopTitle.textContent = '店铺名称';

        const shopGroup = document.createElement('div');
        shopGroup.className = 'char-group';

        const shopChars = Array.from(shopName);
        const selectedShopChars = new Set(shopChars.slice(0, 2)); // 默认选中前两个字

        shopChars.forEach(char => {
            const option = document.createElement('div');
            option.className = `char-option${selectedShopChars.has(char) ? ' selected' : ''}`;
            option.textContent = char;
            option.onclick = () => {
                if (selectedShopChars.has(char)) {
                    selectedShopChars.delete(char);
                    option.classList.remove('selected');
                } else {
                    selectedShopChars.add(char);
                    option.classList.add('selected');
                }
            };
            shopGroup.appendChild(option);
        });

        // 颜色选项
        const colorSection = document.createElement('div');
        colorSection.className = 'modal-section';

        const colorTitle = document.createElement('div');
        colorTitle.className = 'modal-section-title';
        colorTitle.textContent = '颜色名称';

        const colorGroup = document.createElement('div');
        colorGroup.className = 'char-group';

        const colorChars = Array.from(colorText);
        const selectedColorChars = new Set(colorChars); // 默认全选

        colorChars.forEach(char => {
            const option = document.createElement('div');
            option.className = 'char-option selected';
            option.textContent = char;
            option.onclick = () => {
                if (selectedColorChars.has(char)) {
                    selectedColorChars.delete(char);
                    option.classList.remove('selected');
                } else {
                    selectedColorChars.add(char);
                    option.classList.add('selected');
                }
            };
            colorGroup.appendChild(option);
        });

        // 按钮
        const footer = document.createElement('div');
        footer.className = 'modal-footer';

        const cancelButton = document.createElement('button');
        cancelButton.className = 'modal-button modal-button-secondary';
        cancelButton.textContent = '取消';
        cancelButton.onclick = () => modal.remove();

        const confirmButton = document.createElement('button');
        confirmButton.className = 'modal-button modal-button-primary';
        confirmButton.textContent = '确认';
        confirmButton.onclick = () => {
            const selectedShopText = Array.from(selectedShopChars).join('');
            const selectedColorText = Array.from(selectedColorChars).join('');
            onConfirm(selectedShopText, selectedColorText);
            modal.remove();
        };

        // 组装模态框
        shopSection.appendChild(shopTitle);
        shopSection.appendChild(shopGroup);
        colorSection.appendChild(colorTitle);
        colorSection.appendChild(colorGroup);
        footer.appendChild(cancelButton);
        footer.appendChild(confirmButton);

        content.appendChild(title);
        content.appendChild(shopSection);
        content.appendChild(colorSection);
        content.appendChild(footer);
        modal.appendChild(content);

        document.body.appendChild(modal);
    }

    function checkProduct(colorDiv) {
        const shopName = document.querySelector('.merchand-name.pointer')?.textContent.trim() || '';
        const colorText = colorDiv.querySelector('span[style="max-width: 108px;"]')?.textContent.trim() || '';

        createModal(shopName, colorText, (selectedShopText, selectedColorText) => {
            // 获取选中的店铺名拼音首字母
            const shopCondition = getChinesePinyinAbbreviation(selectedShopText) + '*';

            // 获取选中的颜色名
            const colorCondition = selectedColorText;

            const requestData = {
                "ip": "",
                "uid": "20314301",
                "coid": "10079219",
                "page": {
                    "currentPage": 1,
                    "pageSize": 50,
                    "hasPageInfo": true,
                    "pageAction": 1
                },
                "data": {
                    "sku_type": 1,
                    "has_daily_purchase_in_qty": false,
                    "queryFlds": ["pic","i_id","sku_id","name","short_name","properties_value","sale_price","cost_price","category","vc_name","labels","sku_code","supplier_name","weight","enabled","modified","created","creator_name"],
                    "orderBy": "",
                    "enabled": "1",
                    "sku_id": shopCondition,
                    "properties_value": colorCondition,
                    "c_id": ""
                }
            };

            if (DEBUG_MODE) {
                showDebugInfo({
                    step: '发送请求',
                    店铺名称: selectedShopText,
                    店铺拼音首字母: shopCondition,
                    颜色名称: selectedColorText,
                    颜色查询条件: colorCondition,
                    请求数据: requestData
                });
            }
            GM_xmlhttpRequest({
                method: 'POST',
                url: 'https://apiweb.erp321.com/webapi/ItemApi/ItemSku/GetPageListV2?__from=web_component&owner_co_id=10079219&authorize_co_id=10079219',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8',
                    'Origin': 'https://src.erp321.com',
                    'Referer': 'https://src.erp321.com/'
                },
                data: JSON.stringify(requestData),
                onload: function(response) {
                    const result = JSON.parse(response.responseText);
                    
                    // 判断是否为未登录状态
                    if (!result.data) {
                        if (DEBUG_MODE) {
                            showDebugInfo({
                                step: '接收响应',
                                响应数据: result,
                                查重结果: '未连接到聚水潭'
                            });
                        }
                        alert('⚠️ 未连接到聚水潭，请先登录');
                        return;
                    }
                    
                    const hasProducts = result.data.length > 0;
                    
                    if (DEBUG_MODE) {
                        showDebugInfo({
                            step: '接收响应',
                            响应数据: result,
                            查重结果: hasProducts ? '商品已存在' : '商品可以上架'
                        });
                    }
                    
                    alert(hasProducts ? '⚠️ 该商品已存在于ERP系统中' : '✅ 该商品可以上架');
                },
                onerror: function(error) {
                    console.error('请求失败:', error);
                    alert('查询失败，请稍后重试');
                }
            });
        });
    }

    // 监听DOM变化，确保在动态加载的内容中也添加按钮
    const observer = new MutationObserver(() => {
        addCheckButtons();
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

    // 初始化添加按钮
    addCheckButtons();
})();